package com.example.daytest.manyThread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author heyu
 * @title: QiangPiao
 * @description:
 * @date 2022/4/24上午10:49
 */
public class QiangPiao {

    /**
     * 剩余票数
     */
    public int ticket = 100;
    /**
     * 锁
     */
    private Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        new QiangPiao().sell();
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }

    public void sell() {
        new Thread(() -> {
            lockSell();
        }, "检票口1").start();
        new Thread(() -> {
            lockSell();
        }, "检票口2").start();
        new Thread(() -> {
            lockSell();
        }, "检票口3").start();
        new Thread(() -> {
            lockSell();
        }, "检票口4").start();
    }

    private void lockSell() {
        while (true) {
            lock.lock();
            try {
                if (ticket > 0) {
                    ticket--;
                    System.out.println(Thread.currentThread().getName() + "卖出一张票,还剩" + ticket + "张票");
                    Thread.sleep(100);
                } else {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

}


